<script setup lang="ts">
import { ElDialog, ElTree, ElButton } from "element-plus";
import { ref } from "vue";
const isEditor = ref(false);
const visible = ref(false);
const parentId = ref<string | undefined>("");
const treeRef = ref<any>(null);
const currentNodeKey = ref<any>(null);

const props = defineProps({
  menuTree: {
    type: Array,
    default: false,
  },
});

const emit = defineEmits(["setParentMenu"]);

// 打开弹窗
const open = (id: string) => {
  visible.value = true;
  if (parentId) parentId.value = id;
};

// 关闭弹窗
const handleClose = (deno: () => void) => {
  // handleCancel();
  deno();
};

// 參數一 当前点击节点对象
const check = (curNode: any) => {
  if (curNode.id === parentId.value) {
    treeRef.value.setCheckedKeys([]);
    parentId.value = undefined;
    return;
  }
  parentId.value = curNode.id;
  treeRef.value.setCheckedKeys([curNode.id]);
};

// 自定义树节点类名
const customNodeClass = (data: any) => {
  if (data.children && data.children.length > 1) {
    return "is-tow-children";
  }
  return "";
};

const handleOk = () => {
  const node = treeRef.value.getCheckedNodes()[0];
  if (node) {
    emit("setParentMenu", node);
    visible.value = false;
  }
};

// 暴露方法
defineExpose({
  open,
});
</script>

<template>
  <el-dialog
    :title="isEditor ? '修改' : '新增'"
    :before-close="handleClose"
    v-model="visible"
  >
    <el-tree
      ref="treeRef"
      @check="check"
      :current-node-key="currentNodeKey"
      :highlight-current="true"
      :check-on-click-node="false"
      class="menu-tree"
      default-expand-all
      node-key="id"
      :check-strictly="true"
      :props="{
            children: 'children',
            label: (node: any) => node.meta.title,
            class: customNodeClass 
          }"
      :data="props.menuTree"
      show-checkbox
    />
    <template #footer>
      <div class="dialog-footer">
        <el-button type="primary" @click="handleOk">确定</el-button>
      </div>
    </template>
  </el-dialog>
</template>

<style lang="less" scoped>
.menu-tree {
  :deep(.is-tow-children) {
    color: #626aef;
    .el-tree-node__children {
      display: flex;
      flex-wrap: wrap;
    }
  }
}
// :deep(.is-tow-children) {
//   color: #626aef;
// }
</style>
